﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Xml;

namespace Hotpot.Log.Config
{
    ///<summary>
    /// 日志配置
    ///</summary>
    public class LogConfiguration
    {
        ///<summary>
        /// 记录日志的文件路径
        ///</summary>
        public static string LogFilePath
        {
            get
            {
                if (ConfigElement == null) return null;
                XmlNodeList xnl = ConfigElement.GetElementsByTagName("logFile");
                return xnl.Count > 0 ? xnl.Item(0).Attributes["path"].Value : null;
            }
        }
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public static ConnectionStringSettings Conn
        {
            get
            {
                if (ConfigElement == null) return null;
                XmlNodeList xnl = ConfigElement.GetElementsByTagName("logData");
                string connName = xnl.Count > 0 ? xnl.Item(0).Attributes["value"].Value : null;
                if (connName == null)
                    return null;
                return ConfigurationManager.ConnectionStrings[connName];
            }
        }

        public static XmlElement ConfigElement
        {
            get
            {
                XmlElement configElement = ConfigurationManager.GetSection("Hotpot.Log") as XmlElement;
                return configElement;
            }
        }

        /// <summary>
        /// 缓存多少条后一次入库
        /// </summary>
        public static int BufferSize
        {
            get
            {
                if (ConfigElement == null) return 1;
                XmlNodeList xnl = ConfigElement.GetElementsByTagName("bufferSize");
                int bs = 1;
                if (xnl.Count > 0)
                    int.TryParse(xnl.Item(0).Attributes["value"].Value, out bs);
                return bs < 1 ? 1 : bs;
            }
        }

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <returns></returns>
        public static XmlElement GetConfiguration()
        {
            StringBuilder xmlSb = new StringBuilder();

            xmlSb.AppendLine("<Hotpot.Log>");

            if (LogFilePath != null)
            {
                // <!--定义输出到文件中-->
                xmlSb.AppendLine("    <appender name=\"LogFileAppender\" type=\"Hotpot.Log.Appender.FileAppender\">");
                // <!--定义文件存放位置-->
                xmlSb.AppendLine("      <file value=\"" + LogFilePath + "\" />");
                xmlSb.AppendLine("      <appendToFile value=\"true\" />");
                xmlSb.AppendLine("      <layout type=\"Hotpot.Log.Layout.PatternLayout\">");
                //<!--输出格式-->
                //<!--样例：2008-03-26 13:42:32,111 [10] INFO  Hotpot.LogDemo.MainClass [(null)] - info-->
                xmlSb.AppendLine("        <conversionPattern value=\"记录时间：%date 线程ID:[%thread] 日志级别：%-5level 客户端IP：%ip 出错类：%C 出错方法：%M property:[%property{NDC}] - 错误描述：%message%newline\" />");
                xmlSb.AppendLine("      </layout>");
                xmlSb.AppendLine("    </appender>");
            }

            if (Conn != null)
            {
                //<!--定义输出到数据库中-->
                xmlSb.AppendLine("    <appender name=\"AdoNetAppender\" type=\"Hotpot.Log.Appender.AdoNetAppender\">");
                xmlSb.AppendLine("          <bufferSize value=\"" + BufferSize + "\" />");
                if (Conn.ProviderName.ToLower() == "system.data.sqlclient")
                    xmlSb.AppendLine("      <connectionType value=\"System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"/> ");
                else if (Conn.ProviderName.ToLower() == "system.data.oracleclient")
                    xmlSb.AppendLine("      <connectionType value=\"System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" /> ");
                xmlSb.AppendLine("      <connectionString value=\"" + Conn.ConnectionString + "\" />");
                xmlSb.AppendLine("      <commandText value=\"INSERT INTO LogDetails ([LogDate],[Thread],[Level],[Logger],[Message],[IpAddress]) VALUES (@logDate, @thread, @logLevel, @logger,@message,@ipAddress)\" />");
                //<!--定义各个参数-->
                xmlSb.AppendLine("      <parameter>");
                xmlSb.AppendLine("        <parameterName value=\"@logDate\" />");
                xmlSb.AppendLine("        <dbType value=\"String\" />");
                xmlSb.AppendLine("        <size value=\"240\" />");
                xmlSb.AppendLine("        <layout type=\"Hotpot.Log.Layout.PatternLayout\">");
                xmlSb.AppendLine("          <conversionPattern value=\"%date\" />");
                xmlSb.AppendLine("        </layout>");
                xmlSb.AppendLine("      </parameter>");
                xmlSb.AppendLine("      <parameter>");
                xmlSb.AppendLine("        <parameterName value=\"@thread\" />");
                xmlSb.AppendLine("        <dbType value=\"String\" />");
                xmlSb.AppendLine("        <size value=\"240\" />");
                xmlSb.AppendLine("        <layout type=\"Hotpot.Log.Layout.PatternLayout\">");
                xmlSb.AppendLine("          <conversionPattern value=\"%thread\" />");
                xmlSb.AppendLine("        </layout>");
                xmlSb.AppendLine("      </parameter>");
                xmlSb.AppendLine("      <parameter>");
                xmlSb.AppendLine("        <parameterName value=\"@logLevel\" />");
                xmlSb.AppendLine("        <dbType value=\"String\" />");
                xmlSb.AppendLine("        <size value=\"240\" />");
                xmlSb.AppendLine("        <layout type=\"Hotpot.Log.Layout.PatternLayout\">");
                xmlSb.AppendLine("          <conversionPattern value=\"%level\" />");
                xmlSb.AppendLine("        </layout>");
                xmlSb.AppendLine("      </parameter>");
                xmlSb.AppendLine("      <parameter>");
                xmlSb.AppendLine("        <parameterName value=\"@logger\" />");
                xmlSb.AppendLine("        <dbType value=\"String\" />");
                xmlSb.AppendLine("        <size value=\"240\" />");
                xmlSb.AppendLine("        <layout type=\"Hotpot.Log.Layout.PatternLayout\">");
                xmlSb.AppendLine("          <conversionPattern value=\"%logger\" />");
                xmlSb.AppendLine("        </layout>");
                xmlSb.AppendLine("      </parameter>");
                xmlSb.AppendLine("      <parameter>");
                xmlSb.AppendLine("        <parameterName value=\"@message\" />");
                xmlSb.AppendLine("        <dbType value=\"String\" />");
                xmlSb.AppendLine("        <size value=\"240\" />");
                xmlSb.AppendLine("        <layout type=\"Hotpot.Log.Layout.PatternLayout\">");
                xmlSb.AppendLine("          <conversionPattern value=\"%message\" />");
                xmlSb.AppendLine("        </layout>");
                xmlSb.AppendLine("      </parameter>");

                //自定义变量
                xmlSb.AppendLine("      <parameter>");
                xmlSb.AppendLine("        <parameterName value=\"@ipAddress\" />");
                xmlSb.AppendLine("        <dbType value=\"String\" />");
                xmlSb.AppendLine("        <size value=\"240\" />");
                xmlSb.AppendLine("        <layout type=\"Hotpot.Log.Layout.PatternLayout\">");
                xmlSb.AppendLine("          <conversionPattern value=\"%ip\" />");
                xmlSb.AppendLine("        </layout>");
                xmlSb.AppendLine("      </parameter>");

                xmlSb.AppendLine("    </appender>");
            }
            //<!--定义日志的输出媒介，下面定义日志以四种方式输出。也可以下面的按照一种类型或其他类型输出。-->
            xmlSb.AppendLine("    <root>");
            //<!--文件形式记录日志-->
            if (LogFilePath != null)
                xmlSb.AppendLine("      <appender-ref ref=\"LogFileAppender\" />");
            if (Conn != null)
                xmlSb.AppendLine("      <appender-ref ref=\"AdoNetAppender\" />");
            xmlSb.AppendLine("    </root>");
            xmlSb.AppendLine("</Hotpot.Log>");

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmlSb.ToString());

            XmlElement logConfig = xml.DocumentElement;

            return logConfig;
        }
    }
}
